<?php
/**
 * Created by JieHuiLong.
 * E-mail: jiehuilong@icloud.com
 * Date: 2016/9/1
 * Time: 10:00
 * 广告模板管理控制器
 */

namespace App\Http\Controllers\Admin;

use App\Models\Domain;
use App\Models\DomainAttributes;
use App\Models\Group;
use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Admin\DomainController;

use App\Models\Templates;
use App\Models\AdminUser as User;


class TemplatesController extends Controller
{
    protected $fields = [
        'uid' => 1,
        'username' => '',
        'name' => '',
        'mark' => '',
        'source_code' => '',
    ];

    public function __construct(Request $request)
    {
        $strLabel = "<p>//+++++++++++++++++模板标签调用</p>";
        $strLabel .= "<p>微信号：<b class='text-danger'>{{\$wx_num\$}}</b></p>";
        $strLabel .= "<p>微信昵称：<b class='text-danger'>{{\$wx_nickname\$}}</b></p>";
        $strLabel .= "<p>访问IP：<b class='text-danger'>{{\$client_ip\$}}</b></p>";
/*        $strLabel .= "<p>微信号随机值：<b class='text-danger'>{{\$wx_rand$}}</b></p>";
        $strLabel .= "<p>微信号上线时间：<b class='text-danger'>{{\$wx_online$}}</b></p>";
        $strLabel .= "<p>微信号下线时间：<b class='text-danger'>{{\$wx_offline$}}</b></p>";*/
        $strLabel .= "<p>//+++++++++++++++++域名、分组属性标签调用</p>";
        $strLabel .= "<p>属性值: {{属性名称}}</p>";
        $strLabel .= "<p>如：属性值: {{call_tongji}}</p>";
        $this->bladeLable = $strLabel;
    }


    /**
     * 根据requst 返回模板列表数据
     *
     * @return Json
     */

    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = array();
            $data['draw'] = $request->get('draw');
            $start = $request->get('start');
            $length = $request->get('length');
            $order = $request->get('order');
            $columns = $request->get('columns');
            $search = $request->get('search');

            if(auth()->user()->id === 1){
                $data['recordsTotal'] = Templates::count();

                if (strlen($search['value']) > 0) {
                    $data['recordsFiltered'] = Templates::where(function ($query) use ($search) {
                        $query->where('username', 'LIKE', '%' . $search['value'] . '%')
                            ->orWhere('name', 'like', '%' . $search['value'] . '%');
                    })->count();
                    $data['data'] = Templates::where(function ($query) use ($search) {
                        $query->where('username', 'LIKE', '%' . $search['value'] . '%')
                            ->orWhere('name', 'like', '%' . $search['value'] . '%');
                    })->where('uid', auth()->user()->id)
                        ->skip($start)->take($length)
                        ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                        ->get();
                } else {
                    $data['recordsFiltered'] = $data['recordsTotal'];
                    $data['data'] = Templates::where('name','<>','baseTemplate')->skip($start)->take($length)
                        ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                        ->get();
                }
            }else{
                $data['recordsTotal'] = Templates::where('uid', auth()->user()->id)->count();

                if (strlen($search['value']) > 0) {
                    $data['recordsFiltered'] = Templates::where(function ($query) use ($search) {
                        $query->where('username', 'LIKE', '%' . $search['value'] . '%')
                            ->orWhere('name', 'like', '%' . $search['value'] . '%');
                    })->where('uid', auth()->user()->id)->count();
                    $data['data'] = Templates::where(function ($query) use ($search) {
                        $query->where('username', 'LIKE', '%' . $search['value'] . '%')
                            ->orWhere('name', 'like', '%' . $search['value'] . '%');
                    })->where('uid', auth()->user()->id)
                        ->skip($start)->take($length)
                        ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                        ->get();
                } else {
                    $data['recordsFiltered'] = $data['recordsTotal'];
                    $data['data'] = Templates::where('uid', auth()->user()->id)
                        ->skip($start)->take($length)
                        ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                        ->get();
                }
            }

            
            return response()->json($data);
        }
        return view('admin.templates.index');
    }
	//预览
	public function preview($id){ 
		$template = Templates::find((int)$id);
		echo $template->source_code;
	}
    /**
     * 新建数据
     *
     * @return array $data
     */
    public function create()
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }
        $data['userList'] = User::lists('name', 'id');
        $data['bladeLable'] = $this->bladeLable;
        return view('admin.templates.create', $data);
    }

    /**
     * 向数据表新增一条记录
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
		if ($this->validTemplates($request->get('name'))) return redirect()->back()->withErrors("添加失败,模板名重复！");
        $template = new Templates();
        foreach (array_keys($this->fields) as $field) {
            $template->$field = $request->get($field);
        }
        $template->save();
        return redirect('/admin/templates')->withSuccess('添加成功！');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * 编辑数据
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $template = Templates::find((int)$id);
        if (!$template) return redirect('/admin/templates')->withErrors("找不到该模板!");
        foreach (array_keys($this->fields) as $field) {
            $data[$field] = old($field, $template->$field);
        }
        $data['id'] = (int)$id;
        $data['userList'] = User::lists('name', 'id');
        $data['bladeLable'] = $this->bladeLable;
        return view('admin.templates.edit', $data);
    }

    /**
     * 更新数据
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
		if ($this->validTemplates($request->get('name'))&&$this->getTemplateId('name',$request->get('name'))!=$id) return redirect()->back()->withErrors("更新失败,模板名重复！");
        $template = Templates::find((int)$id);
		$name = $template->name;
        foreach (array_keys($this->fields) as $field) {
            $template->$field = $request->get($field);
        }
        $template->save();
		//查询用了该模板的分组
		$groups = Group::where('tpl_id',$id)->orWhere('sh_tpl_id',$id)->get();
		foreach($groups as $group){
			if($name!=$request->get('name')){ //如果改了模板名，才更新对应分组的模板名(冗余)
				$group->template=$request->get('name');//修改分组模板名
				$group->save();
			}
			//调用更新模板函数
			$r = new Request();
			$r->id = $group->id;
			$domain = new DomainController();
			$domain->crossGUpTpl($r);//更新对应分组的模板
		}
		//查询用了该模板的域名
		$domains = Domain::where('tpl_id',$id)->get();
		foreach($domains as $d){
			if($name!=$request->get('name')){ //如果改了模板名，才更新对应域名的模板名(冗余)
				$d->template=$request->get('name');//修改域名模板名
				$d->save();
			}
		}
        return redirect('/admin/templates')->withSuccess('更新成功！');
    }

    /**
     * 删除数据
     *
     * @param  int $id or string ids=>1,2,3,4,5,6
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //获取基础模板ID
        $baseTplId = Templates::where('uid', auth()->user()->id)->where('name', 'baseTemplate')->value('id');
        $newData['tpl_id'] = $baseTplId;
        $newData['template'] = 'baseTemplate';
        if (is_numeric($id)) {
            $tag = Templates::find((int)$id);
            if ($tag) {
                Domain::where('tpl_id', $id)->update($newData);
                Group::where('tpl_id', $id)->update($newData);
                $tag->delete();
            } else {
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        } else {
            $idArr = explode(',', $id);
            $recordRow = Templates::whereIn('id', $idArr)->delete();
            Domain::whereIn('tpl_id', $idArr)->update($newData);
            Group::whereIn('tpl_id', $idArr)->update($newData);
            if (!$recordRow) {
                return redirect()->back()
                    ->withErrors("删除失败");
            }
        }
        return redirect()->back()
            ->withSuccess("删除成功");
    }

    public function leading($id = 0)
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }
        $userList = User::lists('name', 'id');
        $data['userList'] = $userList;
        return view('admin.templates.leading', $data);
    }

    public function import(Request $request)
    {
        $files = $request->allFiles();
		$templates_arr = $this->getTemplateNames();
		$template = new Templates();
        foreach ($files['templates'] as $file) {
            if ($file->isValid()) {
                $originalName = explode('.', $file->getClientOriginalName());
                $name = $originalName[0];
                if (in_array($name,$templates_arr)) continue;
                $source_code = file_get_contents($file);
                
                $data['uid']=auth()->user()->id==1?$request->get('uid'):auth()->user()->id;
                $data['username']=$request->get('username');
                $data['name']=$name;
                $data['mark']=$request->get('mark');
                $data['source_code']=$source_code;
            }
        }
		$template->insert($data);
        return redirect('/admin/templates')->withSuccess('导入成功！');
    }

    public function validTemplates($name)
    {
		$count = Templates::where('name', '=', $name)->where(function($query){
			$query->where('uid',auth()->user()->id)->orWhere('uid',1);
		})->count();
        if ($count > 0) { //如果已经存在
            return true;
        } else {
            return false;
        } 
    }
	public function getTemplateNames(){ //获取所有模板的标题
		return Templates::where(function($query){
			$query->where('uid',auth()->user()->id)->orWhere('uid',1);
		})->lists('name')->toArray();
	}
	//根据条件获取id
	public function getTemplateId($key,$value){
		$tag = Templates::where($key,'=',$value)->first();
		if(!$tag){
			return 0;
		}
		return $tag->id;
	}

}